const express = require('express');
const router = express.Router();
const pool = require('../config/bd');
const { validate: isValidUUID } = require('uuid');

// 消息列表查询（自动会话版）
router.get('/messages', async (req, res) => {
  const connection = await pool.getConnection();
  try {
    // 参数解构与校验
    const { session_id, last_id = 0, pageSize = 20, user_id } = req.query;

    // 双重ID格式验证
    if (!isValidUUID(session_id) || !isValidUUID(user_id)) {
      return res.status(400).json({ code: 400, message: 'ID格式异常' });
    }

    // 自动会话管理
    const [session] = await connection.query(
      `INSERT IGNORE INTO chat_session 
       (id, session_type, creator_id)
       VALUES (?, 'private', ?)`,
      [session_id, user_id]
    );

    // 消息分页查询
    const [messages] = await connection.query(
      `SELECT 
        m.id, m.content, m.msg_type,
        DATE_FORMAT(m.sent_at, '%Y-%m-%d %H:%i:%s') AS sent_at,
        u.id AS sender_id,
        u.nickname AS sender_name,
        u.avatar,
        u.family_name
       FROM message m
       JOIN user u ON m.sender_id = u.id
       WHERE m.session_id = ? AND m.id > ?
       ORDER BY m.sent_at ASC  -- 优化排序方式
       LIMIT ?`,
      [session_id, last_id, parseInt(pageSize)]
    );

    res.json({
      code: 200,
      data: {
        session_type: 'private',
        items: messages
      }
    });

  } catch (error) {
    console.error('消息查询失败:', error);
    res.status(500).json({ code: 500, message: '服务暂不可用' });
  } finally {
    connection.release();
  }
});

// 消息发送接口
router.post('/messages', async (req, res) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const { session_id, content, user_id, msg_type = 'text' } = req.body;
    if (!isValidUUID(session_id) || !isValidUUID(user_id)) {
      throw new Error('ID格式异常');
    }
    if (!content?.trim()) {
      throw new Error('消息内容不能为空');
    }

    // 会话保障机制
    await connection.query(
      `INSERT INTO chat_session 
       (id, session_type, creator_id)
       VALUES (?, 'private', ?)
       ON DUPLICATE KEY UPDATE id = id`,
      [session_id, user_id]
    );

    // 消息持久化
    const [messageResult] = await connection.query(
      `INSERT INTO message 
       (session_id, sender_id, content, msg_type)
       VALUES (?, ?, ?, ?)`,
      [session_id, user_id, content.trim(), msg_type]
    );

    // 结果组装
    const [newMessage] = await connection.query(
      `SELECT 
        m.id, m.content, m.msg_type,
        DATE_FORMAT(m.sent_at, '%Y-%m-%d %H:%i:%s') AS sent_at,
        u.nickname AS sender_name,
        u.avatar
       FROM message m
       JOIN user u ON m.sender_id = u.id
       WHERE m.id = ?`,
      [messageResult.insertId]
    );

    await connection.commit();

    // 实时推送
    try {
      const io = req.app.get('io'); // 关键：从 Express 应用获取实例
      if (io && io.emit) {
        io.to(session_id).emit('new_message', newMessage[0]);
      }
    } catch (emitError) {
      console.error('实时推送失败:', emitError);
    }

    res.status(201).json({ code: 201, data: newMessage[0] });

  } catch (error) {
    await connection.rollback();
    const statusCode = error.message.includes('ID格式') ? 400 : 500;
    res.status(statusCode).json({
      code: statusCode,
      message: error.message.replace('Error: ', '')
    });
  } finally {
    connection.release();
  }
});

module.exports = router;